import json
from time import sleep

import pandas as pd
import requests
import time

from get_config import get_token
from sun_tool_fee_request_params import GlBookSumRequestParams

# === 第一步：发起异步任务 === 总帐输入信息是开始时间
def get_sun_bill(begin_date):
    TOKEN = get_token()
    params = GlBookSumRequestParams(begindate=begin_date)
    request_body = params.to_request_body()
    print(request_body)
    print("\n===== 发起异步任务 =====")
    url_start = "https://jcdz.jcszfw.com/v1/cw/asyncRequest/start"
    headers = {"Token": TOKEN, "Content-Type": "application/json"}

    response = requests.post(url_start, json=request_body, headers=headers)

    if response.status_code != 200:
        print(f"❌ 初始请求失败: {response.status_code} - {response.text}")
        exit(1)

    try:
        start_data = response.json()
        if not start_data.get("result"):
            print(f"❌ 业务失败: {start_data}")
            exit(1)
        sequence_no = start_data["value"]
        print(f"✅ 获取到 sequenceNo: {sequence_no}")
    except Exception as e:
        print(f"❌ 解析初始响应失败: {e}")
        exit(1)

    # === 第二步：轮询查询结果 ===
    url_query = "https://jcdz.jcszfw.com/v1/cw/asyncRequest/queryResult"
    query_body = {"sequenceNo": sequence_no}

    resp = requests.post(url_query, json=query_body, headers=headers)

    try:
        print(resp.text)
        # 取出数据
        data = resp.json()['value']['data']['data']


    except Exception as e:
        sleep(5)
        resp = requests.post(url_query, json=query_body, headers=headers)
        data = resp.json()['value']['data']['data']

    print(data)
    # 转成 DataFrame
    df = pd.DataFrame(data)

    # 映射字段到表头
    df_out = df.rename(columns={
        'accountCode': '科目编码',
        'accountName': '科目名称',
        'accountDate': '期间',
        'summary': '摘要',
        'amountDr': '借方',
        'amountCr': '贷方',
        'balanceDirection': '方向',
        'balanceAmount': '余额'
    })

    # 只保留需要的列，并调整顺序
    df_out = df_out[['科目编码', '科目名称', '期间', '摘要', '借方', '贷方', '方向', '余额']]

    # 保存为 Excel 文件
    df_out.to_excel('库存现金明细.xlsx', index=False)

    print("✅ Excel 已生成：库存现金明细.xlsx")

